package com.itmiaojie.filter;

import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itmiaojie.mapper.MenuMapper;
import com.itmiaojie.pojo.AppHttpCodeEnum;
import com.itmiaojie.pojo.LoginUser;
import com.itmiaojie.pojo.ResponseResult;
import com.itmiaojie.utils.JWTUtils;
import com.itmiaojie.utils.RedisCache;
import com.itmiaojie.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationTokenFilter  extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;


    @Autowired
    private JWTUtils jwtUtils;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求中token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)){
            //如果不存在token 直接放行
            filterChain.doFilter(request,response);
            return;
        }
        //解析获取userid
        DecodedJWT decodedJWT = jwtUtils.verifyToken(token);
        if(decodedJWT==null){
          //  throw new RuntimeException("Token异常");
            //token超时  token非法
            //响应告诉前端需要重新登录
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response,  new ObjectMapper().writeValueAsString(result));
            return;
        }
        //获取userId
        String id = decodedJWT.getClaim("id").asString();
        LoginUser loginUser = redisCache.getCacheObject("bloglogin" + id);
        if (ObjectUtils.isEmpty(loginUser)){
            //说明登录过期  提示重新登录
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, new ObjectMapper().writeValueAsString(result));
            return;
        }

        //TODO 设置权限
        
        //存入上下文
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request,response);

    }
}
